#include<stdio.h>
#include<assert.h>
#include<string.h>
#include<unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include<stdlib.h>
#define MAX 1024
#define ARGC 64
#define SPLITC " "

int split(char* commandstr,char* argv[])
{
    char* tmp = strtok(commandstr,SPLITC);//按字符SPLITC分割字符串
    if(!tmp) return -1;
    int i = 0;
    while(tmp)
    {
        argv[i++] = tmp;
        tmp = strtok(NULL,SPLITC);
    }
    return 0;
}

int main()
{
    while(1)
    {
        char* argv[ARGC] = {NULL};
        //1.读取用户输入的命令
        char commandstr[MAX] = {0};  //从输入流中获取的命令存放在这个缓冲区
        printf("[zhangsan@mymachine currpath]# ");
        fflush(stdout); //Linux中printf遇到/n才会刷新缓冲 区，没有/n需要自己手动刷新
        char* s = fgets(commandstr,sizeof(commandstr),stdin); //获取流字符串
        assert(s);  //如果读取失败返回NULL编译告警（用于自己编写来测试mybash，实际上不需要）
        (void)s;//处理s未被使用带来的警告
        commandstr[strlen(commandstr)-1] = '\0';//fgets会读取'\n'存储到缓冲区中，但这不属于命令的内容，所以置0
        
        //2.分割字符串 "ls -l" -->  "ls" "-l"
        int n = split(commandstr,argv); //argv输出型参数，保存分割后的子串
        if(n != 0) continue;

        //3.创建子进程
        pid_t id = fork();
        if(id == 0)
        {
            execvp(argv[0],argv);
            exit(0);
        }
        int status = 0;
        int ret = waitpid(id,&status,0);
        if(ret > 0)
        {
            printf("waitpid success,return code:%d.\n",WEXITSTATUS(status));
        }
    }
    return 0;
}